﻿using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.Core.ToolHelper;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 销售统计 : Form
    {
        private readonly ISysUserRepository userRepository = new SysUserRepository();
        private readonly ISalesOrderRepository salesOrderRepository = new SalesOrderRepository();
        private readonly IMemberInfoRepository  memberInfoRepository = new MemberInfoRepository();
        public 销售统计()
        {
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        public string UserId { get; set; }
        public string UserName { get; set; }

        public 销售统计(string userId, string userName)
        {
            this.UserId = userId;
            this.UserName = userName;
            InitializeComponent();

            //获取所有的员工信息
            var userList = userRepository.GetList().ToList();
            userList.Insert(0, new SysUser() { UserName = "请选择业务员" });
            cboxUserId.DataSource = userList;
            cboxUserId.DisplayMember = nameof(SysUser.UserName);
            cboxUserId.ValueMember = nameof(SysUser.Id);

            //销售订单类型
            //    药品销售
            //理疗服务销售
            cboxMember.SelectedIndex = 0;
            cboxOrderType.SelectedIndex = 0;

            cboxUserId.SelectedIndexChanged += btnQuery_Click;
            cboxMember.SelectedIndexChanged += btnQuery_Click;
            cboxOrderType.SelectedIndexChanged += btnQuery_Click;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            StringBuilder where = new StringBuilder(" where 1=1 ");
            StringBuilder where_2 = new StringBuilder(" ");
            string userId = cboxUserId.SelectedValue.ToString();
            string beginDate = dtpStart.Text;
            string endDate = dtpEnd.Text;
            string orderType = cboxOrderType.Text;
            string memberType = cboxMember.Text;
            if (orderType == "药品销售")
            {
                where.Append($" and OrderType = 0 ");
            }
            else if (orderType == "理疗服务销售")
            {
                where.Append($" and OrderType = 2 ");
            }

            if (memberType == "会员顾客")
            {
                where.Append($" and ISNULL(MemberId, 0) <> 0 ");
            }
            else if (memberType == "非会员顾客")
            {
                where.Append($" and ISNULL(MemberId, 0) = 0 ");
            }

            int uid = 0;
            if (!userId.IsNullOrEmpty())
            {
                if (int.TryParse(userId, out uid))
                {
                    if (uid > 0)
                    {
                        where.Append($" and UserId = {uid}");
                    }
                }
            }
            if (!beginDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
                where_2.Append($" and CONVERT(VARCHAR,CreateTime,23) >= '{DateTime.Parse(beginDate).ToString("yyyy-MM-dd")}'");
            }
            if (!endDate.IsNullOrEmpty())
            {
                where.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
                where_2.Append($" and CONVERT(VARCHAR,CreateTime,23) <= '{DateTime.Parse(endDate).ToString("yyyy-MM-dd")}'");
            }

            string product = txtProduct.Text.Trim();
            if (!product.IsNullOrEmpty())
            {
                where.Append($" AND (ProductName LIKE '%{product}%' OR ProductCode LIKE '%{product}%')");
            }

            var list = salesOrderRepository.GetSalesReportList(where.ToString());

            dgvData.AutoGenerateColumns = false;
            dgvData.DataSource = list;

            var totalMoney = list.Sum(m => m.TotalMoney);
            var shuaka = memberInfoRepository.GetMoney(where_2.ToString());
            var xianjin = totalMoney - shuaka;
            string moneyMsg = $"合计总金额：{totalMoney.ToString("0#.00")}元, 现金收费：{xianjin.ToString("0#.00")}元, 刷卡收费：{shuaka.ToString("0#.00")}元";
            label3.Text = moneyMsg;
        }

        private void 销售统计_Load(object sender, EventArgs e)
        {
            BindData();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            BindData();
            var path = ExcelHelperForCs.ExportToExcel(dgvData, "销售统计报表");
            MessageBox.Show($"导出成功，文件路径:{path}");
        }
    }
}